package com.yj.forum.interceptor;

import com.yj.forum.common.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${yj-forum.login.url}")
    private String defaultURL;
    /**
     * 预处理(请求的前置处理)回调⽅法<br/>
     * 返回值: <br/>true 流程继续;<br/>
     * false流程中断, 不会再调⽤其他的拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            //已登录状态
            return true;
        }
        //校验URL
        if(!defaultURL.startsWith("/")) {
            defaultURL = "/" +defaultURL;
        }
        //校验不通过，跳转登录界面
        response.sendRedirect(defaultURL);
        return false;
    }
}
